<template>
<view class="container ">
		
	
 <view class="select">
    <van-dropdown-menu>
      <van-dropdown-item @change="activeHandle()" v-model="value_baby" :options="option_baby" />
      <van-dropdown-item @change="activeHandle()" v-model="value_time" :options="option_time" />
    </van-dropdown-menu>
  </view>
  
 
  	<view style="height: 80rpx;">
	</view>
  		 
  	<view style="margin-top: 10rpx;">
		<van-tabs v-model:active="active" type="card">
		  <van-tab title="可视化图展示">
			  <view class="title" >
			  	睡眠状态比例（单位：秒）
			  </view>
			  <view class="echarts" style="" >
			    <l-echart ref="pieChartRef" @finished="init"></l-echart>
			  </view>
			  <view class="title" >
			  	不良姿态次数统计（单位：次）
			  </view>
			  <view class="echarts">
			    <l-echart ref="columnarChartRef" @finished="init"></l-echart>
			  </view>
		  </van-tab>
		  
		  
		  <van-tab title="列表记录展示">
			  
			  <view class="title" >
			  	时长记录（单位：秒）
			  </view>
			  <van-list
			    v-model:loading="loading"
			    :finished="finished"
			    finished-text=""
			    @load="onLoad"
			  >
			    <van-cell v-for="item in recordList" :key="item.id" :title="item.name"  :value="item.value"/>
			  </van-list>
			  
			  <view class="title" >
			  	次数记录（单位：次）
			  </view>
			  <van-list
			    v-model:loading="loading"
			    :finished="finished"
			    finished-text=""
			    @load="onLoad"
			  >
			    <van-cell v-for="item in recordList1" :key="item.id" :title="item.name"  :value="item.value"/>
			  </van-list>
			  
		  </van-tab>
		  
		</van-tabs>
	</view>
  
   
 
  
  
  
  </view>
</template>

<script setup>
import { ref, onMounted, onBeforeMount } from 'vue';
import { onPullDownRefresh } from '@dcloudio/uni-app';
import * as echarts from 'echarts';
import { DropdownMenu, DropdownItem,Tab, Tabs ,List,Toast} from 'vant';
import {getBabysApi} from '../../apis/babyApi.js'
import {getRcordsByCustomApi} from '../../apis/records.js'

const value_baby = ref('0');
const value_time = ref('0');
const itemList = ref([]);


const option_baby = ref([
	 { text: '示例数据', value: '0'},
]);
const option_time = ref([
  { text: '全部', value: '0' },
  { text: '最近一天', value: '1' },
  { text: '最近三天', value: '3' },
  { text: '最近一周', value: '7' },
  { text: '最近一月', value: '30' }
]);

const getItemList = async () => {
	const res=await	getBabysApi()
	itemList.value=res.data
	for (let i = 0; i < itemList.value.length; i++) {
		if(itemList.value.length<=i-1){
			option_baby.value.push({ text: itemList.value[i].name, value: itemList.value[i].id });
		}
		if(itemList.value.length>i-1){
			option_baby.value[i]={ text: itemList.value[i].name, value: itemList.value[i].id }
		}
		
	}
	value_baby.value=option_baby.value[0].value
};

//根据条件查询对应记录数据
const getRecords=async()=>{
	const res=await getRcordsByCustomApi(value_baby.value,value_time.value)
	settingValue(res.records)
}

//下拉菜单选中处理
const activeHandle=async()=>{
	await refresh()
	
}
//可视化展示/列表展示控制参数
const active=ref(0)

const pieChartRef = ref(null);
//饼状图配置对象
const option_pie = {
  title: {
    // text: '婴儿睡眠各姿态占比',
    subtext: '来源于数据采集',
    left: 'center',
	textStyle: {  // 大标题的样式设置
	            fontSize: 14,  // 字体大小
	            fontWeight: 'bold'  // 字体粗细
	        }
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    orient: 'vertical',
    left: 'left',
  },
  series: [
    {
      name: '持续时间',
      type: 'pie',
      radius: '50%',
      data: [
        { value: 0, name: '正常睡眠' },
        { value: 0, name: '睁眼时间' },
        { value: 0, name: '踢腿时间' },
       
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
};

const columnarChartRef = ref(null);
//条形图配置对象
const option_columnar= {
	title: {
	  // text: '婴儿睡眠过程不良姿态次数统计',
	  subtext: '来源于数据采集',
	  left: 'center',
	  textStyle: {  // 大标题的样式设置
	              fontSize: 14,  // 字体大小
	              fontWeight: 'bold'  ,// 字体粗细
				  
	          }
	},
					tooltip: {
						trigger: 'axis',
						axisPointer: {            // 坐标轴指示器，坐标轴触发有效
							type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
						}
					},
					grid: {
						left: '3%',
						right: '4%',
						bottom: '3%',
						containLabel: true
					},
					xAxis: [
						{
							type: 'category',
							data: [ '睡眠','醒着','踢腿'],
							axisTick: {
								alignWithLabel: true
							}
						}
					],
					yAxis: [
						{
							type: 'value',
							min: 0,  // 设置 Y 轴刻度的最小值
							max: 100,  // 设置 Y 轴刻度的最大值
							interval: 10,  // 设置 Y 轴刻度的间隔
							
						}
					],
					series: [
						{
							name: '出现次数',
							type: 'bar',
							barWidth: '60%',
							data: [10, 25, 5, 9]
						}
					]
				}



const recordList=ref([
	{id:0,name:'正常睡眠',value:0},
	{id:1,name:'睁眼时间',value:0},
	{id:2,name:'踢腿时间',value:0},
	
	
])
const recordList1=ref([
	{id:0,name:'正常睡眠',value:0},
	{id:1,name:'睁眼次数',value:0},
	{id:2,name:'踢腿次数',value:0},
	
])
const loading = ref(false);
const finished = ref(false);
const onLoad = () => {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
	  finished.value=true
     
    };
	
//可视化组件初始化-------------------------------------------------------------------------------------
const init = async () => {
  await new Promise(resolve => setTimeout(resolve, 500)); // 延迟时间适当调整
  if (!pieChartRef.value) return;
  const pieChart = await pieChartRef.value.init(echarts);
  pieChart.setOption(option_pie);
  
  
  if (!columnarChartRef.value) return;
  const columnarChart = await columnarChartRef.value.init(echarts);
  columnarChart.setOption(option_columnar);
};


//设置数据到可视化组件
const settingValue=(data)=>{
//设置饼状图---------------------------------------------------------------------------------------------------------------------
	//置空
	option_pie.series[0].data[0].value=0
	option_pie.series[0].data[1].value=0
	option_pie.series[0].data[2].value=0
	
	console.log('记录累加',data)
	//累加多条记录的数据
	for(let i=0;i<data.length;i++){
		//睁眼时间
		option_pie.series[0].data[1].value+=data[i].open_eyes_time
		//睡眠
		option_pie.series[0].data[0].value+=data[i].sleep_time
		
		//踢腿时间
		option_pie.series[0].data[2].value+=data[i].kick_legs_time
		
	}
//设置条形图-------------------------------------------------------------------------------------------------------------------
	
	//置空
	option_columnar.series[0].data[0]=0
	option_columnar.series[0].data[1]=0
	option_columnar.series[0].data[2]=0
	
	//累加多条记录的数据
	for(let i=0;i<data.length;i++){
		
		//睡眠
		option_columnar.series[0].data[0]+=data[i].sleep_count
		//踢腿
		option_columnar.series[0].data[2]+=data[i].kick_legs_count
		//睁眼
		option_columnar.series[0].data[1]+=data[i].open_eyes_count
	}
	//动态调整---------条形图展示的是直观数据量的比较需要根据实际数据量动态调整刻度单位以及范围
	//根据最大值可以粗略确定刻度
	let max=option_columnar.series[0].data[0]
	for(let i=0;i<option_columnar.series[0].data.length;i++){
		if(option_columnar.series[0].data[i]>max){
			max=option_columnar.series[0].data[i]
		}
	}
	
	if(max<=25){
		option_columnar.yAxis[0].max=25
		option_columnar.yAxis[0].interval=5
	}
	else if( max>25&&max<=50){
		option_columnar.yAxis[0].max=50
		option_columnar.yAxis[0].interval=5
	}
	else if(max>50&&max<=100){
		option_columnar.yAxis[0].max=100
		option_columnar.yAxis[0].interval=10
	}
	else if(max>100&&max<=200){
		option_columnar.yAxis[0].max=200
		option_columnar.yAxis[0].interval=20
	}
	else if(max>200&&max<=500){
		option_columnar.yAxis[0].max=500
		option_columnar.yAxis[0].interval=50
	}
	//............
//设置列表时长展示-------------------------------------------------------------------------------------------------------------------
	//置空
	recordList.value[0].value=0
	recordList.value[1].value=0
	recordList.value[2].value=0
	
	
for(let i=0;i<data.length;i++){
	recordList.value[0].value+=data[i].sleep_time
	
	recordList.value[1].value+=data[i].open_eyes_time
	
	recordList.value[2].value+=data[i].kick_legs_time
	
}


//设置列表次数展示-------------------------------------------------------------------------------------------------------------------
	//置空
	recordList1.value[0].value=0
	recordList1.value[1].value=0
	recordList1.value[2].value=0

	

let all_count=0
for(let i=0;i<data.length;i++){
	recordList1.value[0].value+=data[i].sleep_count
	recordList1.value[1].value+=data[i].open_eyes_count
	
	
	recordList1.value[2].value+=data[i].kick_legs_count
	
	

	all_count+=data[i].open_eyes_count
				+data[i].spit_milk_count
				+data[i].kick_legs_count
				+data[i].turnover_count
}

recordList1.value[0].value=all_count

}
//数据刷新
const refresh=async()=>{
	Toast.loading({
	  message: '加载中...',
	  forbidClick: true,
	  duration:300
	});
	await getRecords();
	init()
}

onMounted(async() => {
	if(sessionStorage.getItem('refresh')){
		return
	}
	location.reload();
	sessionStorage.setItem('refresh',1)
	
});


onPullDownRefresh(async()=>{
	await refresh()
	console.log('刷新完毕')
	uni.stopPullDownRefresh()
})
onBeforeMount(async()=>{
  await getItemList();
  await refresh()
})
</script>

<style scoped>
.container{
		background-color: snow;
	}
	.select{
		position: fixed;
		top: 70rpx;
		/* margin: 0 30%; */
		z-index: 999;
		width: 100%;
		
	}
.title{
	display: flex;
	justify-content: center;
	align-items: center;
	height: 80rpx;
	/* background-color:honeydew; */
	color: rgba(43, 66, 76, 1.0);
	font-size: 18px;
	border-radius: 10px;
}

.echarts{
	margin: 0rpx 10rpx 0rpx 17rpx;
	border: 1rpx solid silver;
	width: 716rpx;
	
	border-radius: 25rpx;
	/* background-color:rgba(6, 6, 6, 0.1); */
	box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2);
}
</style>
